package com.abc.queue;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.DelayQueue;

import com.google.gson.Gson;

public class Session {
	
	/**延迟时间，按照秒计时*/
	private static final int _aliveTime = 7;
	
	/**延迟队列*/
	DelayQueue<DelayElements> queue = new DelayQueue<DelayElements>();
	/**模拟session存放信息，保证线程安全*/
	private ConcurrentHashMap<String, Object> userSession = new ConcurrentHashMap<>();
	
	public Session() {
	}

	public void put(String key, Object value) {
		//放入session集合中
		userSession.put(key, value);
		//构造延时队列元素
		DelayElements elements = new DelayElements(key, _aliveTime);
		//溢出之前的队列
		queue.remove(elements);
		//插入新的队列
		queue.add(elements);
		System.out.println("添加session key：" + key + ",value:" + value.toString() + "成功");
	}
	
	public Object get(String key) {
		//从session池中返回对象
		Object result = userSession.get(key);
		if (result != null) {
			DelayElements elements = new DelayElements(key, _aliveTime);
			queue.remove(elements);
			queue.put(elements);
			System.out.println("获取"+key+"成功："+result+",生命周期重新计算");
		}else {
			System.out.println("获取"+key+"失败："+result+"。对象已过期");
		}
		
		return result;
	}
	
	private void sessionGcMethod() throws InterruptedException {
		while (true) {
			//延迟时间内take方法不会获取到值
			//那么将阻塞线程
			DelayElements elements = queue.take();
			queue.remove(elements);
			userSession.remove(elements.getKey());
			System.out.println("删除过期元素key"+elements.getKey());
			Thread.sleep(300);
		}
	}
	
	public void startSession() {
		Thread gcThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					sessionGcMethod();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
			}
		});
		gcThread.setDaemon(true);
		gcThread.setName("gcThread");
		gcThread.start();
	}
	
	
}
